// pages/location/location.js
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
import Toast from '../../components/dist/toast/toast';
var core = require("../../utils/core.js");
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loadingShow: false,
    pageState: 0, // 0 选择社区按钮  1已经选择了
    preuseSqState: 1, //是否有曾用社区  0 没有  1有
    currentCity: '', //当前定位城市
    cityAddreInfo: {}, //位置信息
    ProcessType: 0, //流程类型  0根据定位获取到位置   1 选择城市页面跳转过来    
    modalMaskState: false, //授权提示蒙版
    animation: '',
    shequList: [], //查询出来的社区信息
    shequDataState: true, //true 查询出来的社区信息有数据   false  查询出来的社区信息没有数据
    everchoosedSheQuInfo: '', //曾用社区信息
    choosedShequInfo:'',//已经选择的社区

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    qqmapsdk = new QQMapWX({
      key: 'BRBBZ-QC5KJ-DT7FE-KPV5K-2ZOLS-MGFKR'
    });
    if (options.city) {
      console.log('有参数传过来' + options.city);
      that.setData({
        currentCity: options.city,
        ProcessType: 1
      })
      that.geocoderAddress();

    } else {
      that.setData({
        ProcessType: 0
      })

    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    this.setData({
      modalMaskState: false
    })
    console.log('onshow')
    if (this.data.ProcessType == 0) { //定位流程
      this.getLocation();
    } else if (this.data.ProcessType == 1) { //接受地址
      that.getSheQuInfo();
    }

    wx.getStorage({
      key: 'everchoosedSheQu',
      success: function(res) {
        that.setData({
          everchoosedSheQuInfo: res.data,
          preuseSqState: 1
        })
      },
      fail: function() {
        that.setData({
          everchoosedSheQuInfo: '',
          preuseSqState: 0
        })
      }
    })

    wx.getStorage({//查看已经选的社区
      key: 'choosedSheQu',
      success: function (res) {
        console.log(res)
        that.setData({
          choosedShequInfo: res.data,
          pageState:1
        })

      },
      fail:function(){
        that.setData({
          choosedShequInfo: '',
          pageState:0
        })
      }
    })

    // Toast('yyyy');
  },
  geocoderAddress: function() {
    Toast('tttt');
    var that = this;
    qqmapsdk.geocoder({
      //获取表单传入地址
      address: that.data.currentCity, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
      success: function(res) { //成功后的回调
        console.log(res);
        var latitude = res.result.location.lat;
        var longitude = res.result.location.lng;
        that.setData({
          cityAddreInfo: {
            lat: latitude,
            lng: longitude
          }
        })
      },
      fail: function(error) {
        console.error(error);
      },
      complete: function(res) {
        console.log(res);
      }
    })
  },
  getLocation: function() { //获取位置信息
    var that = this;
    Toast('ffff');
    wx.getSetting({
      success(res) {
        console.log(res.authSetting)
        
        if (res.authSetting['scope.userLocation']) { //用户同意获取地理位置
          wx.getLocation({
            success: function(res) {
              Toast('success');
              var latitude = res.latitude
              var longitude = res.longitude
              qqmapsdk.reverseGeocoder({
                location: {
                  latitude: latitude,
                  longitude: longitude
                },
                success: function(res) {
                  Toast('获取位置信息成功');
                  console.log(JSON.stringify(res));
                  let province = res.result.ad_info.province
                  let city = res.result.ad_info.city;
                  console.log(city);
                  that.setData({
                    currentCity: city,
                    ProcessType: 0,
                    cityAddreInfo: {
                      lat: latitude,
                      lng: longitude
                    }
                  })
                  that.getSheQuInfo();

                },
                fail: function(res) {
                  console.log(res);
                  Toast('获取位置信息失败');
                },
                complete: function(res) {
                  console.log(res);
                  Toast(res);
                }
              })
            },
            fail: function(err) {
              Toast('获取位置信息失败');
            }
          })
          return
        } else { //没授权获取位置
          wx.getLocation({
            success: function(res) {
              Toast('3121');
              console.log(res)
              that.onShow();
            },
            fail: function(err) {
              Toast('5433');
              console.log('获取失败');
              that.setData({
                modalMaskState: true, //授权提示蒙版
              })
            }
          })
        }
      },
      fail:function(){
        Toast('5477733');

      }

    })
  },
  cacanelSq: function() {
    this.setData({
      modalMaskState: false,

    })

  },
  getSheQuInfo: function() { //获取社区信息
    var that = this;
    that.setData({
      loadingShow: true
    })
    core.get("groupapp/index/search_master", {
      address: that.data.currentCity
    }, function(e) {
      console.log(e);
      if (e.error == 0) {
        if (e.list.length == 0) {
          that.setData({
            shequDataState: false,
            loadingShow: false,
          })
        } else {
          that.ProcessingData(e.list);
        }

      } else {
        Toast('获取社区信息失败');
      }
    })
  },

  ProcessingData: function(arr) { //处理数据，先逆解析获取金纬度   再计算每个社区的距离
    var that = this;
    var listarr = arr;
    for (var i = 0; i < listarr.length; i++) {
      (function(i) {
        qqmapsdk.geocoder({
          //获取表单传入地址
          address: listarr[i].address + listarr[i].homename, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
          success: function(res) { //成功后的回调
            console.log(res);
            var res = res.result;
            var latitude = res.location.lat;
            var longitude = res.location.lng;
            listarr[i].cityAddreInfo = {
              lat: latitude,
              lng: longitude
            };
            listarr[i].addressStr = listarr[i].address.split('-').join('')
            qqmapsdk.calculateDistance({
              //mode: 'driving',//可选值：'driving'（驾车）、'walking'（步行），不填默认：'walking',可不填
              from: {
                latitude: that.data.cityAddreInfo.lat,
                longitude: that.data.cityAddreInfo.lng
              }, //若起点有数据则采用起点坐标，若为空默认当前地址
              to: [{
                latitude: latitude,
                longitude: longitude
              }], //终点坐标
              success: function(res) { //成功后的回调
                listarr[i].distance = res.result.elements[0].distance;
                listarr[i].distanceStr = that.prosessNumber(res.result.elements[0].distance);
              },
              fail: function(error) {
                console.error(error);
                Toast('解析社区信息数据失败');
              },
              complete: function(res) {}
            });
          },
          fail: function(error) {
            console.error(error);
          },
          complete: function(res) {
            console.log(res);
          }
        })
      })(i)
    }

    console.log(listarr)
    setTimeout(function() {
      that.setData({
        shequList: listarr,
        loadingShow: false,
        shequDataState: true
      })
    }, 300)




  },
  prosessNumber: function(num) { //处理数字
    var newStr = '';
    var num = parseInt(num) + '';
    console.log(num + '---' + num.length + '--' + typeof num);
    if (num.length == 3) {
      newStr = '0.' + num.substring(0, 1) + 'km'
    } else if (num.length == 4) {
      newStr = num.substring(0, 1) + '.' + num.substring(1, 2) + 'km'
    } else if (num.length == 5) {
      newStr = num.substring(0, 2) + '.' + num.substring(2, 3) + 'km'
    } else if (num.length == 6) {
      newStr = num.substring(0, 3) + '.' + num.substring(3, 4) + 'km'
    } else if (num.length == 7) {
      newStr = num.substring(0, 4) + '.' + num.substring(4, 5) + 'km'
    }

    return newStr
  },
  /**
   * 生命周期函数--监听页面隐藏
   */

  onHide: function() {

  },
  gotoChoose: function() { //跳转选择社区页面
    var that = this;
    wx.getSetting({
      success(res) {
        console.log(res.authSetting)
        if (res.authSetting['scope.userLocation']) { //用户同意获取地理位置
          wx.navigateTo({
            url: '/pages/chooseSheQu/chooseSheQu?city=' + that.data.currentCity,
          })

        } else {
          that.getLocation();
        }
      }
    })


  },
  gotoIndex: function(e) { //选择了社区，返回首页
    var that = this;
    console.log(e);
    var index = e.currentTarget.dataset.index;
    console.log(index)
    wx.setStorage({
      key: 'choosedSheQu',
      data: that.data.shequList[index],
      success: function() {
        wx.switchTab({
          url: '/pages/index/index',
        })
      }
    })
    wx.setStorage({
      key: 'everchoosedSheQu',
      data: that.data.shequList[index],
      success: function() {

      }
    })
  },
  usedSheQu: function() { //点击曾用社区
    wx.getStorage({
      key: 'everchoosedSheQu',
      success: function(res) {
        wx.setStorage({
          key: 'choosedSheQu',
          data: res.data,
          success: function() {
            wx.switchTab({
              url: '/pages/index/index',
            })
          }
        })

      },
    })

  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})